package com.kazu.utils.exception.handler;

import com.kazu.utils.entity.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.HashMap;
import java.util.Map;

import static com.kazu.utils.exception.GlobalExceptionEnum.*;

/**
 * @Author kazu
 * @Date 2023/2/19 13:10
 * @Version 1.0
 */
@SuppressWarnings({"all"})
@Slf4j
@RestControllerAdvice(basePackages = {"com.kazu"})
public class MyExceptionHandler {

	@ExceptionHandler(value = {MethodArgumentNotValidException.class})
	public R handlerValidException(MethodArgumentNotValidException exception) {
		log.error("数据校验出现异常：{}", exception.getMessage());
		
		BindingResult bindingResult = exception.getBindingResult();
		Map<String, Object> exceptionMap = new HashMap<>();
		bindingResult.getFieldErrors().forEach(item -> {
			exceptionMap.put(item.getField(), item.getDefaultMessage());
		});
		return R.error(VALID_EXCEPTION.getCode(), VALID_EXCEPTION.getMsg())
				.put("error", exceptionMap);
	}
	
	@ExceptionHandler(value = {Throwable.class})
	public R handlerOtherException(Exception exception) {
		log.error("未知异常：{}", exception.getMessage());
		exception.printStackTrace();
		return R.error(UNKNOW_EXCEPTION.getCode(), UNKNOW_EXCEPTION.getMsg());
	}

}
